package com.jack.xiaoer.service.impl;

import com.jack.xiaoer.service.error.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

/**
 * Created by Jackaroo Zhang on 2018/12/9.
 */
@Service
public class MailNoifyService {

    @Autowired(required = false)
    private MailSender mailSender;

    private String sendFrom;

    private String sendTo;

    public boolean supported() {
        return mailSender != null;
    }

    public void send(String subject, String message) {
        if (!supported()) {
            return;
        }

        SimpleMailMessage mailMsg = new SimpleMailMessage();
        mailMsg.setFrom(sendFrom);
        mailMsg.setTo(sendTo);
        mailMsg.setSubject(subject);
        mailMsg.setText(message);
        mailSender.send(mailMsg);
    }

    public void sendVerifyCode(String verifyCode, String sendTo) {
        if (!supported()) {
            return;
        }

        SimpleMailMessage mailMsg = new SimpleMailMessage();
        mailMsg.setFrom("jackaroozz@163.com");
        mailMsg.setTo(sendTo);
        mailMsg.setSubject("店小二-用户注册");
        mailMsg.setText("您的验证码为：" + verifyCode + ", 5分钟后过期。");
        try {
            mailSender.send(mailMsg);
        } catch (MailException e) {
            ServiceException serviceException = new ServiceException("邮件发送出现异常");
            serviceException.initCause(e);
            throw serviceException;
        }
    }

    public String getSendFrom() {
        return sendFrom;
    }

    public void setSendFrom(String sendFrom) {
        this.sendFrom = sendFrom;
    }

    public String getSendTo() {
        return sendTo;
    }

    public void setSendTo(String sendTo) {
        this.sendTo = sendTo;
    }
}
